//
//  UIView+BadgeValue.m
//  WBBaseProject
//
//  Created by 吴斌 on 2017/6/30.
//  Copyright © 2017年 吴斌. All rights reserved.
//

#import "UIView+BadgeValue.h"
#import <objc/runtime.h>

static char wb_badgeValueKey;

static CGFloat wb_badgeValue_height = 15;

@implementation UIView (BadgeValue)

- (void)setWb_badgeValue:(NSString *)wb_badgeValue{
    objc_setAssociatedObject(self, &wb_badgeValueKey, wb_badgeValue, OBJC_ASSOCIATION_COPY_NONATOMIC);
    if (wb_badgeValue == nil || [wb_badgeValue isEqualToString:@""] || wb_badgeValue.integerValue <= 0) {
        [self wb_clearBadgeValue];
    }
    else{
        NSAssert([self wb_isAllNumber:wb_badgeValue],@"字符串内容必须是数字");
        CGRect rect = [wb_badgeValue boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:[UIFont smallSystemFontSize]]} context:nil];
        //创建红点
        UIButton *redBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, rect.size.width > wb_badgeValue_height ? rect.size.width + 6 : wb_badgeValue_height, wb_badgeValue_height)];
        redBtn.center = CGPointMake(self.frame.size.width - 3, 3);
        redBtn.tag = 1008611;
        redBtn.layer.cornerRadius = wb_badgeValue_height / 2;
        redBtn.layer.masksToBounds = YES;
        redBtn.titleLabel.font = [UIFont systemFontOfSize:[UIFont smallSystemFontSize]];
        
        redBtn.backgroundColor = [UIColor redColor];
        [redBtn setTitle:wb_badgeValue forState:UIControlStateNormal];
        [self addSubview:redBtn];
    }
}

- (NSString *)wb_badgeValue{
    NSString *badgeValue = objc_getAssociatedObject(self, &wb_badgeValueKey);
    //少于0 重置为0
    if (badgeValue.integerValue < 0) {
        return @"0";
    }
    else{
        return badgeValue;
    }
}

- (void)wb_clearBadgeValue{
    for (UIView *view in self.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
}

//判断是否是全数字
- (BOOL)wb_isAllNumber:(NSString *)text{
    unichar str;
    for (NSInteger index = 0; index < text.length; index ++) {
        str = [text characterAtIndex:index];
        if (isdigit(str)) {
            return YES;
        }
    }
    return NO;
}

- (UIViewController *)getCurrentViewController
{
    for (UIView *view = self; view; view = view.superview)
    {
        UIResponder *nextResponder = [view nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]])
        {
            return (UIViewController *)nextResponder;
        }
    }
    return nil;
}


@end
